package org.px.service;

import org.px.domain.UserIdentity;
import org.px.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.SQLException;


public class UserDao {
    private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    
    /**
     * 根据用户名查询用户
     */
    public UserIdentity findByUsername(String username) throws SQLException {
        String sql = "SELECT * FROM user_identity WHERE username = ?";
        return qr.query(sql, new BeanHandler<>(UserIdentity.class), username);
    }
    
    /**
     * 根据用户ID和密码查询用户
     */
    public UserIdentity findByUserIdAndPassword(String userId, String password) throws SQLException {
        String sql = "SELECT * FROM user_identity WHERE user_id = ? AND password = ?";
        return qr.query(sql, new BeanHandler<>(UserIdentity.class), userId, password);//返回的对象为UserIdentity
    }
    
    /**
     * 注册新用户
     */
    public boolean register(UserIdentity user) throws SQLException {
        String sql = "INSERT INTO user_identity (user_id, username, password, user_type) " +
                    "VALUES (?, ?, ?, ?)";
        // 删除status字段（使用默认值）
        Object[] params = {user.getUser_id(), user.getUsername(), user.getPassword(), user.getUser_type()};
        int count = qr.update(sql, params);
        return count > 0;
    }

    // 修改添加员工方法参数类型
    public boolean addEmployee(String empId, String empName, int deptId) throws SQLException {
        String sql = "INSERT INTO employee (emp_id, emp_name, dept_id) VALUES (?, ?, ?)";
        int count = qr.update(sql, empId, empName, deptId);
        return count > 0;
    }
    
    /**
     * 检查用户ID是否已存在
     */
    public boolean isUserIdExists(String userId) throws SQLException {
        String sql = "SELECT COUNT(*) FROM user_identity WHERE user_id = ?";
        Long count = qr.query(sql, rs -> rs.next() ? rs.getLong(1) : 0L, userId);
        return count > 0;
    }
    
    /**
     * 检查用户名是否已存在
     */
    public boolean isUsernameExists(String username) throws SQLException {
        String sql = "SELECT COUNT(*) FROM user_identity WHERE username = ?";
        Long count = qr.query(sql, rs -> rs.next() ? rs.getLong(1) : 0L, username);
        return count > 0;
    }
    
    // 新增用户删除方法用于补偿操作
    public boolean deleteUser(String userId) throws SQLException {
        String sql = "DELETE FROM user_identity WHERE user_id = ?";
        int count = qr.update(sql, userId);
        return count > 0;
    }
}